<script setup lang="ts">
import useAction from "@/components/play-music-box/action"

const {
  currentTime,
} = useAction()

const musicStore = useMusicStore();

const currentMusicList = computed(() => musicStore.currentMusicList);

const currentMusic = computed(() => musicStore.currentMusic);

const musiclyricList = ref<MusicLyrRecord[]>([]);

const lyricContainer = ref<HTMLElement>(null);

const scrollTop = ref(0);

let lyricBoxHeight = 0;

let lyricItemHeight = 0;


function getLyricHeight() {
  const query = uni.createSelectorQuery().in(this);
  query.select('.audio-lyric').boundingClientRect(rect => {
    lyricBoxHeight = rect.height;
  }).exec();
  query.select('.lyric-item').boundingClientRect(rect => {
    lyricItemHeight = rect.height;
  }).exec();

}

watch(currentTime, (newTime) => {
  if (lyricContainer.value && musiclyricList.value) {
    const activeIndex = musiclyricList.value.findIndex((item: MusicLyrRecord) => newTime >= item.startTime && newTime <= item.endTime);
    if (activeIndex !== -1) {
      if (activeIndex * lyricItemHeight >= lyricBoxHeight / 2) {
        scrollTop.value = (activeIndex + 3) * lyricItemHeight - lyricBoxHeight / 2;
      }
    }
  }
});

watch(currentMusic, (newMusic) => {
  if (newMusic.path) {
    getLyric(currentMusic.value.path);
  }
})

/** 切换播放 */
function musicPlay(path: string) {
  const music = currentMusicList.value.find(music => music.path === path);
  if (!music) {
    musicStore.setCurrentMusic({});
    return;
  }

  if (music.path !== currentMusic.value.path) {
    musicStore.setCurrentMusic(music);
  }
  getLyric(currentMusic.value.path);
}

/** 获取歌词 */
async function getLyric(path: string) {
  const lyricPath = path.replace(/\.(mp3|flac)$/i, '.lrc');

  const lrcText = readFileContent(lyricPath);

  musiclyricList.value = parseLyric(lrcText);

  nextTick(() => {
    getLyricHeight();
  })
}

/** 解析歌词 */
function parseLyric(lrc: string): MusicLyrRecord[] {
  const lines = lrc.split('\n');
  const pattern = /\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/;

  return lines.map((line, index) => {
    const startMatches = line.match(pattern);

    const endtLines = lines[index + 1];
    const endtmMatches = endtLines ? lines[index + 1].match(pattern) : null;

    if (startMatches) {
      const startMin = parseInt(startMatches[1]) * 60;
      const startSec = parseInt(startMatches[2]);
      const startMs = parseInt(startMatches[3].padEnd(3, '0')) / 1000;
      let lrcItem = {
        startTime: startMin + startSec + startMs,
        endTime: startMin + startSec + startMs + 6,
        text: startMatches[4].trim()
      };
      if (endtmMatches) {
        const endmin = parseInt(endtmMatches[1]) * 60;
        const endsec = parseInt(endtmMatches[2]);
        const endms = parseInt(endtmMatches[3].padEnd(3, '0')) / 1000;
        lrcItem.endTime = endmin + endsec + endms;
      }

      return lrcItem;
    }
    return { time: 0, text: line.trim() };
  });
}

// 添加媒体键监听
onLoad(options => {
  if (options.path) {
    musicPlay(options.path)
  }
});


</script>

<template>
  <view class="audio-container">
    <!-- 封面信息 -->
    <view class="audio-info">
      <image
          class="poster"
          src="/static/image/audiopaly/music-a.png"
          mode="aspectFill"
      />
      <view class="meta" v-if="currentMusic">
        <text class="title">{{ currentMusic.musicName }}</text>
        <text class="author">{{ currentMusic.author }}</text>
      </view>
    </view>
    <scroll-view class="audio-lyric" scroll-y="true" :scroll-top="scrollTop" ref="lyricContainer">
      <view v-for="(item, index) in musiclyricList"
            :key="index"
            class="lyric-item"
            :class="{ active: currentTime >= item.startTime && currentTime <= item.endTime }"
            :ref="'lyricLine' + index">
        {{ item.text }}
      </view>
    </scroll-view>
    <play-music-box class="play-music-more" auto-play />
  </view>
</template>

<style scoped lang="scss">
.audio-container {
  padding: 30rpx;
  background: #756c5d;

  .audio-info {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;

    .poster {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;

      .title {
        display: block;
        font-size: 34rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
        color: $uni-white;
      }

      .author {
        font-size: 26rpx;
        color: $uni-extra-color;
      }
    }
  }

  .audio-lyric {
    padding: 20rpx 0;
    height: calc(100vh - 398rpx);
    text-align: center;
    color: $uni-white;

    .lyric-item {
      min-height: 20px;
      line-height: 20rpx;
      font-size: 14px;
      transition: all 0.5s;
    }

    .active {
      font-size: 18px;
      line-height: 25rpx;
      color: #ffff67;

    }
  }

}
</style>

